<?php
class Answer_Service_Answer extends Phpfox_Service {
    function __construct()
    {
        $this->_sTable = Phpfox::getT('brodev_answer_');
        $this->_sTableUser = Phpfox::getT('user');
    }
    private function _getTable($sName) {
        return $this->_sTable.$sName;
    }
    /**
     * get question from database
     * @param string $sFields
     * @param array $aCondition
     * @param int $iPage
     * @param int $iLimit
     * @return array
     */
    public function get($sFields='', $aCondition, $sOrder ='a.created', $iPage = '', $iLimit = '') {
        $sFields = ($sFields == '' || $sFields =='*') ? 'a.*' : $sFields;
        $oDb = Phpfox::getLib('database');
        $iCount = $this->database()
            ->select('COUNT(*)')
            ->from($this->_getTable('answer'),'a')
            ->where($this->getCondition($aCondition))
            ->execute('getField');
       $oDb ->select($sFields .', q.title as question_title, q.title2 as question_title2,  q.image as question_image, q.is_ab as question_is_ab,u.user_image as image, u.user_name as user_name, u.full_name as full_name, count(up.id) as voteup, count(down.id) as votedown, count(checkup.id) as checkup, count(checkdown.id) as checkdown, (count(up.id) + count(down.id)) as vote ')
            ->from($this->_getTable('answer'), 'a')
            ->where($this->getCondition($aCondition))
            ->leftJoin($this->_getTable('question'), 'q', 'a.question_id = q.id')
            ->leftJoin($this->_sTableUser, 'u', 'a.user_id = u.user_id')
            ->leftJoin($this->_getTable('point'), 'up', 'up.action = 3 and up.up = 1 and  up.answer_id = a.id')
            ->leftJoin($this->_getTable('point'), 'down', 'down.action = 3 and down.up = 0 and  down.answer_id = a.id')
            ->leftJoin($this->_getTable('point'), 'checkup', 'checkup.action = 3 and checkup.up = 1 and  checkup.answer_id = a.id and checkup.user_id = '. Phpfox::getUserId())
            ->leftJoin($this->_getTable('point'), 'checkdown', 'checkdown.action = 3 and checkdown.up = 0 and  checkdown.answer_id = a.id and checkdown.user_id = '. Phpfox::getUserId())
            ->order($sOrder)
            ->group('a.id');
        if ($iLimit != '') {
            $iPage = ($iPage == '') ? 0 : $iPage;
            $oDb->limit($iPage, $iLimit, $iCount);
        }
        $aRecords = $oDb->execute('getRows');

        if ($iCount > 0) {
            foreach ($aRecords as $iKey => $aRow)
            {
                $aLike = Phpfox::getService('like')->getLikes('answer_answer', $aRow['id']);
                if (count($aLike) > 0) {
                    $aRecords[$iKey]['isLiked'] = true;
                } else {
                    $aRecords[$iKey]['isLiked'] = false;
                }
                $aRecords[$iKey]['point'] = Phpfox::getService('answer.point')->getPoint($aRow['user_id']);
                $aRecords[$iKey]['label'] = Phpfox::getService('answer.level')->getLabel($aRow['user_id']);
            }
        }

        return array(
            'data' => $aRecords,
            'count' => $iCount
        );
    }

    /**
     * change to condition string in sql query
     * @param array $aCondition
     * @return string
     *
     */
    private  function getCondition ($Condition) {
        $sWhere ="1 ";
        if (!is_array($Condition)) {
            if (trim($Condition) != "") {
                $sWhere .= "AND ". $Condition. " ";
            }
        }
        else {
            foreach ($Condition as $iKey => $Val) {
                $sWhere .= "AND ";
                $sOperation = strstr($iKey, " ");
                if (trim($sOperation) != "") {
                    $sWhere .= $iKey ." " . $Val ." ";
                }
                else {
                    $sWhere .= $iKey ." = ". $Val ." ";
                }
            }
        }
        return $sWhere;
    }
    /**
     * insert or update category to database
     * @param $aVal
     * @param $iId
     * @return bool
     */
    public function saveDatabase($aVal) {
        $iId = $aVal['id'];
        $aCondition = array('id ' => (int) $iId);
        $oParseInput = Phpfox::getLib('parse.input');
        $aVal['detail'] = (empty($aVal['detail']) ? null : $oParseInput->prepare($aVal['detail']));
        if ( !$this->isExist($aCondition) ) {
            $aVal['created'] = PHPFOX_TIME;

            $iId = $this->database()
                ->insert($this->_getTable('answer'), $aVal)
            ;
            if (!$iId)
            {
                return false;
            }
            else {
                $aPoint = array(
                    'action' => 2,
                    'question_id' => $aVal['question_id'] ,
                    'user_id' => $aVal['user_id'],
                    'answer_id' => $iId,
                    'created' => date("Y-m-d H:i:s", time())

                );
                Phpfox::getService('feed.process')->add('answer_answer', $iId);
                Phpfox::getService('answer.point')->saveDatabase($aPoint);
                return true;
            }
        }
        else {
            return $this->database()->update($this->_getTable('answer'), $aVal, "id = " . $iId);
        }
    }
    /**
     * sort array by key
     * @param $aArray
     * @param $sKey
     * @return array
     */
    function subval_sort($aArray,$sKey) {
        foreach($aArray as $k=>$v) {
            $aTemp[$k] = strtolower($v[$sKey]);
        }

        arsort($aTemp);

        foreach($aTemp as $key=>$val) {
            $aResult[] = $aArray[$key];
        }
        return $aResult;
    }
    /**
     * get 1 question from database with condition
     * @param array $aCondition
     * @return array
     */
    public function getForEdit( $aCondition ) {
        $aAnswer = $this->database()
            ->select('a.*, q.title as question_title, q.image as question_image')
            ->from($this->_getTable('answer'), 'a')
            ->where( $this->getCondition($aCondition))
            ->leftJoin($this->_sTableUser, 'u', 'a.user_id = u.user_id')
            ->leftJoin($this->_getTable('question'), 'q', 'a.question_id = q.id')
            ->execute('getRow');
        return array(
            'data'=>$aAnswer
        );
    }

    /**
     * Check Exist
     * @param array $aCondition
     * @return bool
     */
    public function isExist($aCondition) {
        $iCount = $this->database()
            ->select('count(*)')
            ->from($this->_getTable('answer'))
            ->where($this->getCondition($aCondition))
            ->execute('getField');
        if ($iCount > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    /**
     * delete category from database      *
     * @param $iId
     * @return bool
     */
    public function delete($iId) {

        $aCondition = array('answer_id = '.$iId);
        $aPoints = Phpfox::getService('answer.point')->getListNoPage('*',$aCondition);
        $aPoints = $aPoints['data'];
        foreach($aPoints as $aItem) {
            Phpfox::getService('answer.point')->delete($aItem['id']);
        }
        Phpfox::getService('feed.process')->delete('answer_answer', $iId);
        Phpfox::getService('feed.process')->delete('answer_voteup', $iId);
        Phpfox::getService('feed.process')->delete('answer_votedown', $iId);
        Phpfox::getService('feed.process')->delete('answer_correct', $iId);
        return  $this->database()->delete($this->_getTable('answer'), 'id = ' . $iId);
    }

    /**
     * get total answer from one question
     * @param int $iQuestionId
     * @return int mixed
     */
    public function getTotal($iQuestionId) {
        $iCount = $this->database()
            ->select('count(*)')
            ->from($this->_getTable('answer'))
            ->where('question_id = '. $iQuestionId)
            ->execute('getField');
        return $iCount;
    }
}
if (defined('PHPFOX')) { $v7f6a05a4 = PHPFOX_DIR . 'file/cache/'; } 